// pages/details/details.js
var app = getApp(); //获取应用实例
const quote = app.globalData.quote;
const createPoster = require('./makePoster.js') //引入制作海报逻辑
const mta = quote.mta;
const api = quote.api;

const path = quote.paths;
const tools = quote.tools;
const Authorize = quote.Authorize

const recorder = app.globalData.recorder; //引入录音对象
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器

Page({
    /**
     * 页面的初始数据
     */
    data: {
        path: path,
        QID: null, //视频id
        videoUrl: app.globalData.videoUrl, //后台地址
        playUrl: null, //视频地址
        RecordFilePath: '', //临时录音文件地址
        ImgUrl: '', //视频封面地址
        videoImgUrl: null,
        Title: '一起来配音吧！',
        hidePop: true,
        hideTranslate: true,
        // 单词翻译部分
        scrollTop: null, //单词查询滚动条位置
        maskTips: true, //新版功能提示
        slideAnimate: false, //滑入滑出动画
        sentence: '.', //不为空是为了防止dispose方法中报出一个不影响结果的报错
        wordList: null, //句子拆分成的单词数组
        currentWord: null, //当前选中单词下标
        wordResult: null, //单词查询结果
        //页面状态参数
        "isStart": false, //学习开始
        "isRecord": false, //正在录音
        "isComplete": false, //录音完成
        "isVideoEnd": false, //视频播放完
        "isMute": false, //是否静音
        "listening": false, //是否正在听录音
        "remain": 0, //播放录音剩余时间
        "hideEnglishText": false, //隐藏英文原文
        "hideStop": true, //隐藏停止按钮  
        "hidePlayText": true, //隐藏播放录音文本
        "hideRecordText": true, //隐藏开始录音文本
        "hidePlay": true, //隐藏播放按钮
        "hideRecord": false, //隐藏录音按钮
        "hideAudition": true, //隐藏试听按钮
        "hideNext": true, //隐藏下一句
        "hideSubmit": false, //隐藏提交
        "hideRemake": true, //隐藏重录
        "hideModal": true, //是否隐藏模态框
        "hideMask": true, //隐藏海报蒙版框
        "hideScore": true, //隐藏得分数据
        "hidevideo": true, //是否隐藏视频
        "showModalFrame": false, //是否隐藏模态框
        "nocancel": true,
        "isEnd": false, //学习结束
        "isRemakeClick": false, //重录按钮是否点击
        "isNextClick": false, //下一句按钮是否点击
        "isStartRecordClick": false, //点击录音按钮是否点击
        "isPlayRecordClick": false, //播放录音按钮是否点击
        "isStopPlayRecord": false, //停止播放按钮是否点击
        "isButtonClick": false, //是否有按钮被点击
        "isSubmitClick": false, //提交按钮是否被点击
        "runAnimation": false, //是否加载动画
        "isLoading": false, //正在保存图片中
        //用户得分情况
        "Score": 0, //录音得分
        "TotalScore": 0, //用户总得分
        "ScoreList": [], //用户得分列表
        "Accuracy": null, //准确度
        "Fluency": null, //流畅度
        //录音提交参数和得分情况
        "result": null, //录音结果
        "record_scale": 100, //分制
        "Overall": 0, //综合得分
        "Integrity": 0, //完整度
        "Pronunciation": 0, //发音得分
        "Rhythm": 0, //节律度
        // 学习序列
        "index": 0, //文件片段序列
        "lastSentence": false, //是不是最后一句
        "startTime": 0, //片段开始时间
        "RemainingTime": 0, //剩余时间
        "timeStampList": [], //解析后的时间段列表
        //字幕文件列表
        "SrtList": null,
        "SrtListIdxEn": null,
        windowWidth: app.globalData.windowWidth,
        windowHeight: app.globalData.windowHeight,
        scale: app.globalData.scale,
        Dailychallenge: null,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this
        console.log('打开练习页获取到的数据', options);

     

        var scene = decodeURIComponent(options.scene)
        var sceneArr = scene.split("&")
        if (sceneArr.length == 2) {
            // app.globalData.openId = sceneArr[0];
            that.setData({
                QID: sceneArr[1],
            })
            that.getVideoInfoData()
            return
        }

        if (!options.hasOwnProperty("QID")) {
            wx.switchTab({
                url: `/${path.index}`,
            })
            return
        }
        that.setData({
            QID: options.QID,
            Dailychallenge: options.Dailychallenge || 0,
            hidevideo: options.Dailychallenge == 1,
            showModalFrame: options.Dailychallenge == 1
        })

        //分享获取票据信息
        wx.showShareMenu({
                withShareTicket: true,
                success: function(res) {
                    // 分享成功
                    console.log('练习页面分享成功', res)
                },
                fail: function(res) {
                    // 分享失败
                    console.log(res)
                }
            })
            //请求视频字幕数据
        var obj = app.globalData.videoCacheObj[options.QID];
        console.log('缓存中的字幕和视频地址', app.globalData.videoCacheObj)
        if (obj) {
          console.log(222222)
            that.setData({
                url: obj[0],
                SrtList: obj[1],
                videoImgUrl: obj[2]
            })
            let index = that.data.index;
            that.setData({
                "SrtListIdxEn": obj[1][index]["English"].split(" ")
            })
        } else {
          console.log(111111)
            that.getVideoInfoData()
        }
    },
    onShow: function(options) {
        var that = this;

        console.log('onshow', options);
        Authorize.checkRecord(function(res) {
            if (!res) {
                that.setData({
                    hidePop: false,
                    hidevideo: true
                })
            } else {
                that.setData({
                    hidePop: true,
                    hidevideo: false
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {
        var that = this;

        //上传开始练习信息
        that.uploadInfoData();

        //获得modalFrame组件  
        // that.modalFrame = that.selectComponent("#modalFrame")
        that.authorizePop = that.selectComponent('#authorizePop')

        // 获取视频操作对象
        that.videoContext = wx.createVideoContext('myVideo');

        // 播放指定视频
        console.log('播放视频，that.videoContext.play');
        that.videoContext.play()

        // 转换数据
        console.log('转换数据1', that.transformTime());

        //渲染完成后，打印页面数据集
        console.log('页面数据集', that.data)

        //音频播放器状态
        innerAudioContext.onPlay((res) => {

            console.log('音频开始播放', res)
        })
        innerAudioContext.onStop((res) => {

            console.log('音频停止播放', res)
        })
        innerAudioContext.onEnded((res) => {

            console.log('音频结束播放', res)
        })
        innerAudioContext.onError((res) => {
            console.log('音频播放错误', res)
        })

    },

    onHide: function() {
        var that = this;
        recorder.stop();
        that.setData({
            "hideModal": true
        })
    },

    onUnload: function() {
        var that = this;

        that.videoContext.pause();

        recorder.cancel({
            //取消录音完成回调
            onStop: function(ret) {
                console.log("手动返回取消了录音：", ret)
            }
        });
    },

    //视频播放回调
    videoPlay: function(params) {
        var that = this;

        if (that.data.isRecord || that.data.isPlayRecordClick) {
            return
        }
        that.setData({
            isMute: false
        })
    },
    //视频暂停播放回调
    videoPause: function(params) {
        var that = this;

        that.setData({
            isMute: true
        })
    },
    //视频缓冲
    videoWaiting: function(params) {
        var that = this;

        that.setData({
            hidevideo: false
        })
        console.log('视频缓冲...')
    },
    //收集formId
    saveFormId: tools.saveFormId,

    //处理每次得分添加到用户的得分数组中
    joinScoreList: function() {
        var that = this;
        var index = that.data.index;

        // 每次得分产生的对象
        var newScore = {
            "index": index,
            "Score": that.data.Score,
            "Overall": that.data.Overall, //综合得分
            "Integrity": that.data.Integrity, //完整度
            "Fluency": that.data.Rhythm, //节律度改为流畅度
            "Pronunciation": that.data.Pronunciation, //发音得分
        };

        var scoreArr = that.data.ScoreList;
        scoreArr[index] = newScore;
        that.setData({
            "ScoreList": scoreArr,
        })
    },

    // 计算最终得分
    CalculationScore: function() {
        var that = this;

        var ScoreList = that.data.ScoreList;
        var Fluency = 0; //节律度改为流畅度
        var Pronunciation = 0; //发音得分
        var Integrity = 0; //完整度
        var Overall = 0; //综合得分
        var TotalScore = 0; //总分

        for (var i = 0; i < ScoreList.length; i++) {
            var ele = ScoreList[i];
            Fluency += ele.Fluency / ScoreList.length;
            Pronunciation += ele.Pronunciation / ScoreList.length;
            Integrity += ele.Integrity / ScoreList.length;
            TotalScore += ele.Overall / ScoreList.length;
        }

        // 设定最终分数
        that.setData({
            "Accuracy": Math.round(Pronunciation * 10) / 10, //准确度
            "Fluency": Math.round(Fluency * 10) / 10, //流畅度
            "Integrity": Math.round(Integrity * 10) / 10, //完整度
            "TotalScore": Math.round(TotalScore * 10) / 10, //总分
        })

    },

    //把字幕列表中的每一个时间段解析到新数组中
    transformTime: function() {
        var that = this;
        var SrtList = that.data.SrtList;
        console.log('字幕列表', SrtList)
        if (!SrtList) {
            console.log('字幕文件从地球上消失了')
            return;
        }
        for (var i = 0; i < SrtList.length; i++) {
            var StartTime = Math.floor(that.decodeTimestamp(SrtList[i]['Start_End'])[0] - 0);
            var EndTime = Math.ceil(that.decodeTimestamp(SrtList[i]['Start_End'])[1] - 0);
            //计算时间段
            var timeInterval = EndTime - StartTime + 1;
            //将时间段对应的开始时间放入新数组中
            that.data.timeStampList.push({
                startTime: StartTime,
                timeInterval: timeInterval
            })
        }
        console.log('转换数据成功，transformTime', that.data.timeStampList)
        that.setData({
            "RemainingTime": that.data.timeStampList[0].timeInterval
        })

    },

    //把字符串形式的时间解析成秒
    decodeTimestamp: function(timestamp) {
        var timeArr = [];
        //转换字符串的正则方法.replace(/ *( *, *)+ */g,'.')
        timestamp.split('-').forEach(function(v) {
            timeArr.push(v.replace(/ *( *, *)+ */g, '.'))
        });
        return timeArr;
    },


    //播放指定时间段视频，index播放序列,**增加视频播完后的回调函数callback**
    playVideoOnTime: function(index, callback) {
        var that = this;

        that.videoContext.pause();
        var t1 = that.data.timeStampList[index].startTime || 0.1;
        var timelong = that.data.timeStampList[index].timeInterval;

        // 开始播放视频
        console.log('playVideoOnTime');
        that.videoContext.seek(t1)
        that.videoContext.play()

        //开定时器前清除之前的定时器
        clearInterval(that.timer_video);
        //开定时器
        that.timer_video = setInterval(function() {
            timelong--;
            if (timelong == 0) { //当播完视频
                clearInterval(that.timer_video);
                that.videoContext.pause();

                //当视频播完后执行回调
                typeof callback == 'function' && callback();
            }
        }, 1000);

    },

    //暂停播放视频函数
    stopVideo: function() {
        var that = this;

        console.log('stopVideo');
        this.videoContext.pause()

        that.setData({
            "isVideoEnd": true,
            "hideRemake": false,
            "hideNext": false,
            "hideStop": true,
            "hidePlay": false,
        })
    },

    // 播放录音函数
    playRecord: function() {
        var that = this;
        var index = that.data.index;
        console.log('播放录音playRecord');

        // app.aldstat.sendEvent('录音-录音后-点击试听');
        // mta.Event.stat("record_afterrecord_clickauditions", {})

        if (that.data.isButtonClick) {
            console.log('已经有按钮被点击，请稍后再点')
            return
        }
        //点击后把状态设置为已经点击
        that.setData({
            "isButtonClick": true
        })

        //0.5s后释放状态
        setTimeout(function() {
            that.setData({
                "isButtonClick": false
            })
        }, 500);

        if (that.data.isPlayRecordClick) {
            console.log('播放按钮已经点击')
            return
        }

        // 开定时器，记录录音时间
        clearInterval(that.timer_paly);
        var remain = that.data.timeStampList[index].timeInterval;
        that.timer_paly = setInterval(function() {
            that.setData({
                "remain": --remain
            });
            console.log('剩余播放时间', remain);
            // 当剩余时间为零时，停止录音
            if (remain <= 0) {
                that.setData({
                    "listening": false,
                    "remain": that.data.timeStampList[index].timeInterval,
                });
                clearInterval(that.timer_paly);
            }
        }, 1000);

        //设置页面相关状态
        that.setData({
            "isMute": true,
            "isVideoEnd": true,
            "isPlayRecordClick": true,
            "listening": true,
        })

        // 播放当前段录音
        innerAudioContext.play();

        // 播放当前片段视频
        that.playVideoOnTime(index, function() {

            console.log('innerAudioContext.paused')
            innerAudioContext.paused

            that.setData({
                "isPlayRecordClick": false
            })
        })
    },

    //结束播放录音
    endRecord: function() {
        var that = this;
        var index = that.data.index;
        console.log('结束播放录音endRecord');

        clearInterval(that.timer_paly);
        that.setData({
            "listening": false,
            "remain": that.data.timeStampList[index].timeInterval,
        });
        that.stopPlayRecord();
    },

    //停止播放录音
    stopPlayRecord: function() {
        var that = this;
        var index = that.data.index;
        console.log('停止播放录音stopPlayRecord');

        clearInterval(that.timer_paly);

        if (that.data.isStopPlayRecordClick) {
            console.log('停止播放录音按钮已经点击')
            return;
        }

        that.videoContext.pause();
        innerAudioContext.stop();

        that.setData({
            "hidePlay": false,
            "isStopPlayRecordClick": true,
            "isPlayRecordClick": false
        })

        setTimeout(function() {
            that.setData({
                "isStopPlayRecordClick": false
            })
        }, 500);

    },

    tapNext: function(params) {
        var that = this;

        if (!that.data.lastSentence) {
            // app.aldstat.sendEvent('录音-录音后-点击评测');
            // mta.Event.stat("record_afterrecord_clickevaluating", {});
        } else {
            // app.aldstat.sendEvent('录音-录音后-点击下一句');
            // mta.Event.stat("record_afterrecord_clicknext", {});
        }

        if (that.data.index != that.data.SrtList.length - 1) {
            that.getNext();

        } else {
            app.globalData.AlreadyPracticed[that.data.QID] = true;
            that.submit();
        }
        return;
    },

    // 获取下一句
    getNext: function() {
        var that = this;
        var SrtListLenght = that.data.SrtList.length

        if (that.data.isButtonClick) {
            console.log('已经有按钮被点击，请稍后再点')
            return
        }
        //点击后把状态设置为已经点击
        that.setData({
            "isButtonClick": true
        })

        //0.5s后释放状态
        setTimeout(function() {
            that.setData({
                "isButtonClick": false
            })
        }, 500);

        if (that.data.isNextClick) {
            console.log('下一句已经点击')
            return;
        }

        that.setData({
            "isNextClick": true,
        });
        //上传录音到公司服务器完成
        that.updateRecording(function(res) {
            console.log('上传完成', res)
            if (res.statusCode != 200) {
                wx.showModal({
                    title: '温馨提示',
                    content: '您的录音出错了，请重新录制',
                    showCancel: false,
                    success: function(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            that.setData({
                                "hideEnglishText": false,
                                "isMute": false,
                                "hideRecord": false,
                                "hidePlay": true,
                                "hidePlayText": true,
                                "hideRecordText": false,
                                "hideNext": true,
                                "hideRemake": true,
                                "hideScore": true,
                                "runAnimation": false,
                            })
                            return;
                        }
                    }
                })
                return;
            } else {
                // 切换到下一句字幕
                var index = (that.data.index + 1) > (SrtListLenght - 1) ? (SrtListLenght - 1) : (that.data.index + 1);

                that.setData({
                    "index": index,
                    "lastSentence": index == SrtListLenght - 1,
                    "hideEnglishText": false,
                    "isMute": false,
                    "hideRecord": false,
                    "hidePlay": true,
                    "hidePlayText": true,
                    "hideRecordText": false,
                    "hideNext": true,
                    "hideRemake": true,
                    "hideScore": true,
                    "runAnimation": false,
                    "TotalScore": that.data.TotalScore + that.data.Score,
                    "isNextClick": true,
                    "RemainingTime": that.data.timeStampList[index].timeInterval,
                    "SrtListIdxEn": that.data.SrtList[index]["English"].split(" ")
                });

                // 播放下一句的视频
                that.playVideoOnTime(that.data.index, function() {
                    that.setData({
                        "isVideoEnd": true,
                        "isMute": true
                    })
                });
            }
        });

    },

    // 重录函数
    remake: function() {
        var that = this;
        console.log('重录');

        if (that.data.isButtonClick) {
            console.log('已经有按钮被点击，请稍后再点')
            return
        }
        //点击后把状态设置为已经点击
        that.setData({
            "isButtonClick": true
        })

        //0.5s后释放状态
        setTimeout(function() {
            that.setData({
                "isButtonClick": false
            })
        }, 500);

        //如果重录按钮已经点击则忽略这次点击
        if (that.data.isRemakeClick) {
            console.log('按钮已经点击')
            return
        }

        //更新得分列表
        var ScoreList = that.data.ScoreList;
        ScoreList.pop();

        //播放当前位置的视频
        that.setData({
            "isMute": false,
            "hideNext": true,
        })

        var index = that.data.index;
        that.playVideoOnTime(index);

        that.setData({
            "hideEnglishText": true,
            "hidePlayText": true,
            "hideRecordText": false,
            "hidePlay": true,
            "hideRecord": false,
            "runAnimation": false,
            "ScoreList": ScoreList,
            "hideRemake": true,
            "isEnd": false,
            "isRemakeClick": false,
        })

    },

    // 提交录音
    submit: function() {
        var that = this

        console.log('submit');
        // 弹出提示框提示正在上传

        wx.showLoading({
            title: '等待最终评分',
            mask: true,
        })

        that.CalculationScore(); //计算最终得分
        that.updateRecording(function(err) {
            console.log('上传录音完成', err)
        }); //上传录音到公司服务器


        setTimeout(function() {
            wx.hideLoading();
            // 跳转页面
            setTimeout(function() {
                // 如果是挑战视频跳转到挑战排行榜页面
                if (that.data.Dailychallenge == 1) {
                    wx.redirectTo({
                        url: '/' + path.dailyChallenge + "?QID=" + that.data.QID
                    })
                    return
                }
                // 如果不是挑战视频跳转到得分页面
                wx.redirectTo({
                    url: '/' + path.scorePreview + "?QID=" + that.data.QID + "&finishBtnClicked=false"
                })
            })
        }, 2000)

        if (!app.globalData.AccountsTimes && app.globalData.DefaultTimes == 1) {
            //将默认练习次数置零
            app.globalData.DefaultTimes = 0; //每日挑战的默认练习次数
            wx.setStorageSync('firstOpen', { 'date': new Date().getDate(), 'DefaultTimes': 0 });
        }

    },

    //上传录音到公司服务器**上传到公司服务器完成后执行回调callback**
    updateRecording: function(callback) {
        var that = this;
        var index = that.data.index;

        var srtitem = that.data.SrtList[index];
        console.log('srtitem', srtitem)
        var obj = {
            "VID": srtitem["VID"],
            "VoiceDuration": that.data.timeStampList[index]["timeInterval"],
            "VoiceText": srtitem["English"],
            "UpfileName": that.data.RecordFilePath,
            "Sort_Id": srtitem["SortId"],
            "Score": that.data.Overall
        }
        var voiceJson = JSON.stringify(obj); //json转字符串
        var formDic = {
            'AppKey': app.globalData.appkey,
            'OpenId': app.globalData.openId,
            'QID': that.data.QID,
            'IsEnd': index == (that.data.SrtList.length - 1) ? 2 : 1,
            "TotalScore": index == (that.data.SrtList.length - 1) ? that.data.TotalScore * that.data.SrtList.length : "0",
            'action': 'WechatSumbitMyVoice',
            'TotalCount': that.data.SrtList.length,
            "CompleteDegree": that.data.Integrity, //完整度
            "FluencyDegree": that.data.Fluency, //节律度
            "AccuracyDegree": that.data.Accuracy, //发音得分
            'VoiceJson': voiceJson, //voiceJson
            'IsChallenge': that.data.Dailychallenge //是否是挑战视频
        }
        console.log('上传到公司的数据', formDic)

        const uploadTask = wx.uploadFile({
            url: app.globalData.apiUrl + app.globalData.baseAshx,
            filePath: that.data.RecordFilePath, //that.data.RecordFilePath
            name: that.data.RecordFilePath, //that.data.RecordFilePath
            header: {
                'content-type': 'multipart/form-data'
            },
            formData: formDic,
            success: function(res) {
                console.log("上传成功返回的数据", res)

            },
            fail: function(err) {
                console.log("上传失败返回的数据", err)
                that.setData({
                    "isSubmitClick": false,
                });
            },
            complete: function(res) {
                wx.hideLoading();
                //上传录音完成后执行回调
                typeof callback == 'function' && callback(res);
            }
        })
    },

    // 去排行榜页面
    gotoRanklist: function() {
        var that = this

        wx.navigateTo({
            url: '/' + path.rankList + "?QID=" + that.data.QID
        })
    },

    // 从本地拿取字幕文件数据
    setPlayTime: function(srtData) {
        var that = this
        var srtArr = srtData.data.arr
        for (var i = 0; i < srtArr.length; i++) {
            if (parseInt(that.data.QID) == srtArr[i].Qid) {
                console.log("全部:", srtArr, "当前:", srtArr[i].SrtList)
                that.setData({
                    SrtList: srtArr[i].SrtList,
                })
            }
        }
    },

    //录音开始函数
    record_start: function() {
        var that = this;
        var index = that.data.index;


        if (that.data.isStartRecordClick) {
            console.log('录音按钮已经点击');
            return;
        }

        that.setData({
            "isStartRecordClick": true,
            "hideNext": true,
            "hidePlay": true
        })

        //录音提交参数
        var scoreCfg = {
            coreType: 'sent.eval', //测评类型 that.data.record_coreType
            refText: that.data.SrtList[index].English, //文本 that.data.record_refText
            scale: 100, //分制 parseInt(that.data.record_scale)
            precision: 1, //精度 parseFloat(record_precision.toFixed(1))
            dict_type: 'kk', //音素字典选项 that.data.dict_type[that.data.record_dict] 
            slack: 0 //宽松度 parseFloat(slack.toFixed(1))
        }

        console.log('录音参数:', scoreCfg, "录音时长:", that.data.timeStampList[index].timeInterval)

        console.log('recorder.stop') //接口代码中的录音管理器
        recorder.stop()

        recorder.start({
            duration: that.data.timeStampList[index].timeInterval * 1000, //录音时长 that.data.record_time * 1000 
            serverParams: scoreCfg, //录音传参
            //开始录音成功回调
            onStart: function() {
                console.log("录音开始onStart");
                that.setData({
                    "isRecord": true,
                    "isStart": true,
                    "isMute": true, //设置静音
                    "hideRecord": true,
                    "hideRecordText": true,
                    "RemainingTime": that.data.timeStampList[index].timeInterval,
                });

                //播放当前句的视频
                that.playVideoOnTime(index);

                // 开定时器，记录录音时间
                clearInterval(that.timer_record);
                that.timer_record = setInterval(function() {
                    that.setData({
                        "RemainingTime": that.data.RemainingTime - 1
                    });
                    console.log('剩余时间', that.data.RemainingTime);
                    // 当剩余时间为零时，停止录音
                    if (that.data.RemainingTime <= 0) {
                        clearInterval(that.timer_record);
                        setTimeout(() => {
                            that.setData({
                                "isRecord": false,
                            });

                        }, 200);

                    }
                }, 980);

                setTimeout(() => {
                    tools.countDown(null, that.data.timeStampList[index].timeInterval, that.data.scale);
                }, 100);
            },
            //录音完成回调
            onStop: function(ret) {

                console.log('录音完成onStop', ret);
                innerAudioContext.src = ret.tempFilePath

                that.setData({
                    "RecordFilePath": ret.tempFilePath
                })
                wx.showLoading({
                    title: '评分中...',
                })
                recorder.stop();
                //录音完成提示震动
                wx.vibrateShort({
                    complete: function(res) {
                        console.log('录音完成打开震动', res)
                    }
                });
            },
            //获取评分结果回调
            onScore: function(ret) {
                console.log("录音评分结果onScore", JSON.parse(ret));

                wx.hideLoading();

                that.show_result(ret); //展现得分信息

                // app.aldstat.sendEvent('录音 - 录音提交成功');
                // mta.Event.stat("record_recordsuccess", {});

                var result = JSON.parse(ret).result;
                if (result) {
                    console.log('得分结果', result);
                    that.setData({
                        "hideEnglishText": true, //隐藏英文原句
                        "hideScore": false, //隐藏得分
                        "runAnimation": true,
                        "Score": result.overall, //录音得分
                        "Overall": result.overall, //录音综合得分
                        "Integrity": result.integrity, //完整度
                        "Rhythm": result.fluency, //原来的节律度改为流畅度
                        "Pronunciation": result.pronunciation, //发音得分
                        "remain": that.data.timeStampList[index].timeInterval,
                    })

                    // 将得分添加到得分列表中
                    that.joinScoreList();

                    //500毫秒后设置页面状态
                    setTimeout(function() {
                        that.setData({
                            "isRecord": false,
                            "isMute": false,
                            "hidePlay": false,
                            "hideNext": false,
                            "lastSentence": index == (that.data.SrtList.length - 1),
                            "isNextClick": false,
                            "isStartRecordClick": false
                        })
                    }, 500)
                } else { //获取得分失败重录
                    wx.hideLoading();
                    wx.showModal({
                        title: '温馨提示',
                        content: 'Ai老师计算失误',
                        showCancel: false,
                        confirmText: '再录一次',
                        success: function(res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                                wx.hideLoading();
                                that.setData({
                                    "hideRecord": false,
                                    "hideRecordText": false,
                                    "hidePlay": true,
                                    "hideRemake": true, //隐藏重录
                                    "isStartRecordClick": false,
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                }
            },
            //过程发生错误回调，目前有如下情况会触发：1、录音异常中止 2、远程服务器连接异常中止
            onError: function(ret) {
                setTimeout(function() {
                    wx.hideLoading()
                }, 2000)
                console.log("录音过程发生错误回调onError", ret);
                that.setData({
                    "isRecord": false,
                })
                recorder.stop();
                switch (ret.errCode) {
                    case 30001:
                        //还未完成录音服务器就返回报错信息
                        that.onErrorToRecord('网络状况不佳,请重新录制');
                        break;
                    case 30002:
                        //正在录音时服务器与客户端主动断开，评分服务器出错
                        that.onErrorToRecord('网络状况不佳,请重新录制');
                        break;
                    case 30003:
                        //客户端网络中断或者其他异常导致客户端主动与服务器断开连接
                        that.onErrorToRecord('网络不太好哦，请保持您的网络畅通');
                        break;
                    case 30004:
                        //本地录音机出错，执行错误的停止开始录音流程
                        that.onErrorToRecord('录音出问题了哦，请再试一次');
                        break;
                    default:
                        console.log('error', ret.errMsg)
                }
            },
            fail: function(ret) {
                console.log("录音接口调用失败fail", ret);
                wx.hideLoading();
                wx.showModal({
                    title: '温馨提示',
                    content: '录音出了小差错，请重新录制',
                    showCancel: false,
                    success: function(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            that.setData({
                                "hideRecord": false,
                                "hideRecordText": false,
                                "hidePlay": true,
                                "hideRemake": true, //隐藏重录
                                "isStartRecordClick": false,
                            })
                        }
                    }
                })
                recorder.stop();
            },
        })
        // if (parseInt(that.data.Score) > 0) {
        //     app.aldstat.sendEvent('录音-录音后-点击重新录音');
        //     mta.Event.stat("record_afterrecord_clickrerecord", {});
        // } else {
        //     app.aldstat.sendEvent('录音-录音前-点击录音');
        //     mta.Event.stat("record_beforerecord_clickrecord", {});
        // }
    },

    //录音停止
    record_stop: function() {
        console.log('record_stop')
        recorder.stop({
            success: function(ret) {
                console.log("录音停止success", ret)
            },
            fail: function(ret) {
                console.log("录音停止fail", ret)
            },
            complete: function(ret) {
                console.log("录音停止complete", ret)
            }
        })

    },

    //点击模态框确认
    confirm: function() {
        this.setData({
            "hideModal": true,
            "hideRecord": false,
            "hideRecordText": false,
            "hidePlay": true,
            "hideRemake": true, //隐藏重录
            "isStartRecordClick": false,
        });
    },

    //录音出错后执行的重录代码
    onErrorToRecord(tip) {
        var that = this;
        wx.showModal({
            title: '温馨提示',
            content: tip,
            showCancel: false,
            confirmText: '确定',
            success: function(res) {
                that.setData({
                    "isRecord": false,
                    "hidePlay": true,
                    "hideNext": true, //隐藏重录
                    "isStartRecordClick": false,
                })
                recorder.stop();
            },
        })
    },

    //获取到数据后存入页面
    show_result(result) {
        var data = JSON.parse(result) || {}
        if (data.hasOwnProperty("result")) {
            this.setData({
                result: data.result
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(res) {
        var that = this;
        console.log('res', res)
        if (res.from === 'button') {
            // console.log(res.target);
            that.setData({
                showModalFrame: false,
            })
            return {
                title: '像电影明星一样说英语！',
                desc: '天天口语秀',
                path: `${path.details}?QID=${that.data.QID}&shareOpenId=${app.globalData.openId}`,
                // path:'',
                imageUrl: `${path.images}shareImg.jpg`,
                success: function(res) {
                    console.log('转发成功', res);
                    wx.showShareMenu({
                        // 要求小程序返回分享目标信息
                        withShareTicket: true
                    });
                },
                fail: function(err) {
                    console.log('转发失败', err)
                },
                complete: function(res) {
                    that.setData({
                        hidevideo: false
                    })
                }
            }
        } else {
            return {
                title: '口语天天练，成就一口地道外语',
                desc: '天天口语秀',
                path: `${path.details}?QID=${that.data.QID}&shareOpenId=${app.globalData.openId}`,
                success: function(res) {
                    //转发成功
                    console.log('练习页面转发成功', res)
                    wx.getShareInfo({
                        shareTicket: res.shareTickets[0],
                        success: function(res) { console.log('获取分享练习页面的票据信息成功', res) },
                        fail: function(res) { console.log(res) },
                        complete: function(res) { console.log(res) }
                    })
                },
                fail: function(res) {
                    //转发失败
                }
            }
        }

    },

    //上传开始练习信息
    uploadInfoData: function() {
        var that = this

        console.log(app.globalData)

        var dataDic = {
            QID: that.data.QID,
            OpenId: app.globalData.openId,
            ImgUrl: app.globalData.userInfo.avatarUrl,
            nickName: app.globalData.userInfo.nickName,
        };

        console.log('请求开始练习接口的参数', dataDic);
        //选择视频进入练习
        api.methodWechatStartLearning({
            dataDic,
            success: (res) => {
                console.log(res);
            },
            fail: (res) => {
                console.log(res);
            },
            complete: (res) => {
                console.log(res.data);
            }
        });
    },

    getVideoInfoData: function() {
        var that = this

        var dataDic = {
            Qid: that.data.QID,
            OpenId: app.globalData.openId,
        };
       //获取视频信息和字幕
        api.methodWechatGetVideoInfo({
            dataDic,
            success: (res) => {
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    console.log('获取视频信息成功', res.data)
                    var url = `${app.globalData.videoUrl}${res.data.data.VideoUrl}`;

                    that.setData({
                        url: url,
                        videoImgUrl: app.globalData.videoUrl + res.data.data.ImgUrl,
                        SrtList: res.data.data.VideoSrtList,
                        Title: res.data.data.Title
                    })
                    that.transformTime();

                    //缓存视频和字幕
                    var SrtList = res.data.data.VideoSrtList;
                    let index = that.data.index;
                    that.setData({
                        "SrtListIdxEn": SrtList[index]["English"].split(" ")
                    })
                    if (!app.globalData.videoCacheObj[that.data.QID]) {
                        wx.downloadFile({
                            url: url,
                            complete: function(res) {
                                console.log('下载视频的临时地址', res, );
                                if (res.statusCode === 200) {
                                    //将数据存入app.js中
                                    app.globalData.videoCacheObj[that.data.QID] = [res.tempFilePath, SrtList, that.data.videoImgUrl];
                                    console.log(app.globalData.videoCacheObj)
                                }
                            }
                        })
                    }
                }
            },
            fail: (res) => {
                console.log(res);
                wx.showModal({
                    title: '温馨提示',
                    showCancel: false,
                    content: '请检查当前网络状况',
                });
            },
            complete: (res) => {
                wx.hideLoading();
                console.log(res.data);
            }
        });
    },
    //制作海报
    createPoster: function() {
        var that = this;

        // createPoster(that, path, tools, app, mta);
        createPoster(that, path, tools, app);
    },

    //保存canvas截图
    saveToAlbum: function() {
        var that = this;

        // if (parseInt(that.data.Score) > 0) {
        //     app.aldstat.sendEvent('录音-录音后-点击保存图片');
        //     mta.Event.stat("record_afterrecord_saveimage", {});
        // } else {
        //     app.aldstat.sendEvent('录音-录音前-点击保存图片');
        //     mta.Event.stat("record_beforerecord_saveimage", {});
        // }

        that.setData({
            isLoading: true
        });
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 311,
            height: 468,
            destWidth: 311 * that.data.scale * 5,
            destHeight: 468 * that.data.scale * 5,
            canvasId: 'poster',
            fileType: 'jpg',
            success: function(res) {
                console.log('生成图片的地址', res.tempFilePath)
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success(res) {
                        console.log('保存文件成功', res);
                        wx.showToast({
                            title: '海报保存成功',
                            icon: 'success',
                            duration: 1000
                        })
                        // if (parseInt(that.data.Score) > 0) {
                        //     app.aldstat.sendEvent('录音-录音后-保存图片成功');
                        //     mta.Event.stat("record_afterrecord_saveimagesuccess", {});
                        // } else {
                        //     app.aldstat.sendEvent('录音-录音前-保存图片成功');
                        //     mta.Event.stat("record_beforerecord_saveimagesuccess", {});
                        // }
                        that.setData({
                            isLoading: false,
                            hideMask: true
                        })
                    }
                })
            }
        })
    },

    //取消保存到相册
    cancelSave: function() {
        var that = this;

        // if (parseInt(that.data.Score) > 0) {
        //     app.aldstat.sendEvent('录音-录音后-点击关闭海报');
        //     mta.Event.stat("record_afterrecord_closeposter", {});
        // } else {
        //     app.aldstat.sendEvent('录音-录音前-点击关闭海报');
        //     mta.Event.stat("record_beforerecord_closeposter", {});
        // }

        var ctx = wx.createCanvasContext('poster')
        ctx.clearRect(0, 0, 300, 450)
        ctx.draw()

        that.setData({
            hideMask: true
        })
    },

    //取消按钮被点击
    onCancelTap: function(e) {
        var that = this;

        console.log('取消按钮已点击', e);
        that.setData({
            hidevideo: false
        })

        wx.navigateBack({
            delta: 1, // 回退前 delta(默认为1) 页面
        })
    },

    //确定按钮被点击
    onConfirmTap(e) {
        var that = this;

        console.log('确定按钮已点击', e);
        var type = e.detail.type;
        var detail = e.detail.detail;
        if (type == 'getUserInfo') {

        } else if (type == 'openSetting') {

        }
    },
    // 单词翻译部分
    tapWord: function(e) {
        console.log('点击单词', e)
        let that = this;
        let reg = /[a-z]+[\-\']?[a-z]*/ig; //匹配单词正则
        let word = e.currentTarget.dataset.word;
        if (word[word.length - 1] == '.') {
            let wordArr = word.split('');
            wordArr.pop();
            word = wordArr.join('')
        }
        if (word.search(reg) == -1) {
            console.log("点击的是标点符号或数字")
            return
        }
        app.aldstat.sendEvent('练口语-查询单词次数');
        that.setData({
            hidevideo: true,
            hideTranslate: false,
            currentWord: e.currentTarget.dataset.id,
            scrollTop: 0
        })
        let dataDic = {
            word: word
        }
        api.methodGetWordDetail({
            dataDic,
            success: (res) => {
                console.log("查询单词成功", res.data)
                if (res.data.status_code != 0) {
                    console.log("暂无此单词")
                    that.setData({
                        wordResult: null
                    })
                    return
                }
                that.setData({
                    wordResult: res.data.data,
                    slideAnimate: true,
                    hidevideo: true
                })
            },
            fail: (res) => {
                console.log("查询单词失败", res);
            },
            complete: (res) => {
                console.log(res.data);
            },
        })
    },
    //翻译模块淡出
    slideOut() {
        let that = this;
        this.setData({
            slideAnimate: false,
            currentWord: null,
            // hidevideo: false,
            // hideTranslate: true
        })
        setTimeout(() => {
            that.setData({
                hideTranslate: true,
                hidevideo: false
            })
        }, 1000);
    },
    // 播放单词发音
    playWord(e) {
        // innerAudioContext.pause();
        let src = e.currentTarget.dataset.audio;
        innerAudioContext.src = src;
        innerAudioContext.play();
        innerAudioContext.onError((res) => {
            console.log(res.errMsg)
            console.log(res.errCode)
        })
        console.log("播放发音地址", src)
    },
    // 隐藏新版功能提示
    hiddenMask() {
        this.setData({
            maskTips: true
        })
        wx.setStorage({
            key: "maskTips",
            data: "true"
        })
    }
})